/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.web.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.cx1.model.Blog;
import org.cx1.model.Photo;
import org.cx1.model.Place;
import org.cx1.model.utils.KBlogTypeIDs;
import org.cx1.model.utils.ServiceResponse;
import org.cx1.model.utils.SystemProperties;
import org.cx1.service.api.IBlogService;
import org.cx1.service.api.IPhotoService;
import org.cx1.service.impl.DBlogService;
import org.cx1.service.impl.DPhotoService;
import org.cx1.service.impl.MBlogService;
import org.cx1.service.utils.ImageProcessor;
import org.cx1.web.controller.action.BlogAction;
import org.cx1.web.controller.action.PlaceAction;
import org.cx1.web.utils.SessionUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author ECH
 */
public class BlogController extends BaseController {

    //private IBlogService blogService = new MBlogService();
    
    private IBlogService blogService = new DBlogService();
    private IPhotoService photoService = new DPhotoService();
    
    public BlogController() {
    }

    protected ModelAndView handleRequestInternal( HttpServletRequest request,
                                                  HttpServletResponse response) throws Exception {
        ModelAndView mav = new ModelAndView();
        Map map = new HashMap();
        
        boolean loggedin = false;
        String userID = SessionUtils.getUserID(request.getSession());   
        
        if (!StringUtils.isEmpty(userID)) {
            loggedin = true;
            map.put("loggedin", loggedin);
        }
        
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        if (ServletFileUpload.isMultipartContent(request)) {
            parameterMap = this.getMultipartFormParams(request);
        } 
        else {
            parameterMap = this.getFormParams(request);
        }

        Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");
        int action = StringUtils.isEmpty(formfields.get("a")) ? 0 : Integer.parseInt(formfields.get("a"));
           
        switch (action) {
            case BlogAction.READ_ALL: {
                readAll(mav, map, request);
                break;
            }
            case BlogAction.READ: {
                read(mav, map, request);
                break;
            }
            case BlogAction.CREATE: {                
                if (loggedin) {
                    create(mav, map, request);
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                } 
                break;
            }
            case BlogAction.UPDATE: {            
                if (loggedin) {
                    update(mav, map, request);   
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                } 
                break;
            }    
            case BlogAction.DELETE: {   
                if (loggedin) {
                delete(mav, map, request); 
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                } 
                break;
            }
            case BlogAction.UPDATE_PHOTO: {
                if (loggedin) {
                    updatePhoto(mav, map, request, parameterMap);
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case BlogAction.CREATE_PHOTO: {
                if (loggedin) {
                    createPhoto(mav, map, request, parameterMap);
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case BlogAction.REMOVE_PHOTO: {
                if (loggedin) {
                    deletePhoto(mav, map, request, parameterMap);
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            default: {
                readAll(mav, map, request);
                break;
            }
        }

        map.put("host", SystemProperties.SYSTEM_HOST);
        map.put("port", SystemProperties.SYSTEM_PORT);
        map.put("props", this.getSystemProperties());
        
        mav.addObject("model", map);
        return mav;
    }
    
    private void readAll(ModelAndView mav, Map map, HttpServletRequest request) {
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        
        ServiceResponse<List<Blog>> response1 = blogService.readAll(0, 0);
        map.put("blogs", response1.getResponse());        
        mav.setViewName("blogall");
    }
    
    private void read(ModelAndView mav, Map map, HttpServletRequest request) {
        String id = request.getParameter("id");        
        
        ServiceResponse<Blog> response = blogService.read(id);                
        map.put("blog", response.getResponse());
        mav.setViewName("blog");
    }
    
    private void create(ModelAndView mav, Map map, HttpServletRequest request) {
        if (!StringUtils.isEmpty(request.getParameter("s"))) {           
            String blogTypeID = request.getParameter("blogTypeID");            
            String title = request.getParameter("title");
            String body = request.getParameter("body");     
            String shortBody = request.getParameter("shortBody");     
            
            String authorName = request.getParameter("authorName");
            String authorGPlus = request.getParameter("authorGPlus");
                    
            String tagIDs = request.getParameter("tagIDs");
            String placeIDs = request.getParameter("placeIDs");
            
            Blog blog = new Blog(); 
            
            blog.setBlogTypeID(blogTypeID);            
            blog.setTitle(title);
            blog.setBody(body);
            blog.setShortBody(shortBody);
            
            blog.setAuthorName(authorName);
            blog.setAuthorGPlus(authorGPlus);
            
            blog.setTagIDs(StringUtils.isEmpty(tagIDs) ? null : Arrays.asList(tagIDs.split("\\s*,\\s*")));
            blog.setPlaceIDs(StringUtils.isEmpty(placeIDs) ? null : Arrays.asList(placeIDs.split("\\s*,\\s*")));
            
            ServiceResponse<String> response = blogService.create(blog);
            map.put("blog", response.getResponse());
            mav.setView(new RedirectView("blog.htm?a="+BlogAction.READ+"&id="+response.getResponse()));   
        }
        else {
            mav.setViewName("blogadd");
        }
    }
    
    private void update(ModelAndView mav, Map map, HttpServletRequest request) {
        if (!StringUtils.isEmpty(request.getParameter("s"))) {             
            String blogTypeID = request.getParameter("blogTypeID");         
            String id = request.getParameter("id");             
            String title = request.getParameter("title");
            String body = request.getParameter("body");
            String shortBody = request.getParameter("shortBody");
                    
            String authorName = request.getParameter("authorName");
            String authorGPlus = request.getParameter("authorGPlus");
            
            String tagIDs = request.getParameter("tagIDs");
            String placeIDs = request.getParameter("placeIDs");
                                    
            ServiceResponse<Blog> response1 = blogService.read(id);              
            Blog blog = response1.getResponse();          

            if (blog != null) {                          
                blog.setBlogTypeID(blogTypeID);            
                blog.setTitle(title);
                blog.setBody(body);
                blog.setShortBody(shortBody);
                
                blog.setAuthorName(authorName);
                blog.setAuthorGPlus(authorGPlus);
            
                blog.setTagIDs(StringUtils.isEmpty(tagIDs) ? null : Arrays.asList(tagIDs.split("\\s*,\\s*")));
                blog.setPlaceIDs(StringUtils.isEmpty(placeIDs) ? null : Arrays.asList(placeIDs.split("\\s*,\\s*")));
            
                ServiceResponse<Boolean> response = blogService.update(blog);
                map.put("blog", response.getResponse());
                mav.setView(new RedirectView("blog.htm?a="+BlogAction.READ+"&id="+id));
            }
            else {
                mav.setView(new RedirectView("blog.htm"));                
            }
        }        
        else {                       
            String id = request.getParameter("id");    
            ServiceResponse<Blog> response = blogService.read(id);  
                        
            map.put("blog", response.getResponse());   
            mav.setViewName("blogedit");
        }
    }
    
    private void delete(ModelAndView mav, Map map, HttpServletRequest request) {        
        String id = request.getParameter("id");
        ServiceResponse<Boolean> response = blogService.delete(id);        
        mav.setView(new RedirectView("blog.htm?a="+BlogAction.READ_ALL));
    }
    
    private void readAllBlog(ModelAndView mav, Map map, HttpServletRequest request) {
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        
        ServiceResponse<List<Blog>> response1 = blogService.readAllByType(0, 0, KBlogTypeIDs.RESOURCE);
        map.put("blogs", response1.getResponse());        
        mav.setViewName("blogall_blogs");
    }
    
    private void readAllResource(ModelAndView mav, Map map, HttpServletRequest request) {
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        
        ServiceResponse<List<Blog>> response1 = blogService.readAllByType(0, 0, KBlogTypeIDs.RESOURCE);
        map.put("blogs", response1.getResponse());        
        mav.setViewName("blogall_resources");
    }
    
    private void createPhoto(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");
        List<Photo> photos = new ArrayList<Photo>();
        
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);       
        String blogID = formfields.get("id"); 
        
        try {
            if (isMultipart) {
                List filefields = (List) parameterMap.get("filefields");
                Iterator iterator = filefields.iterator();

                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (!item.isFormField()) {
                        String fileName = item.getName();
                        
                        if (!StringUtils.isEmpty(fileName)) {
                            String ext = "";
                            
                            if (StringUtils.containsIgnoreCase(fileName, ".jpg")) {
                                ext = ".jpg";
                            }
                            if (StringUtils.containsIgnoreCase(fileName, ".png")) {
                                ext = ".png";
                            }
                            
                            String genFileName = UUID.randomUUID().toString();                        
                            fileName = genFileName;
                            fileName = fileName + ext;
                            
                            String root = getServletContext().getRealPath("/");
                            root = SystemProperties.PHOTO_DIRECTORY;
                            File path = new File(root);

                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }
                            File uploadedFile = new File(path + "/" + fileName );
                                                        
                            if (!uploadedFile.exists()) {
                                //CX: write photo
                                item.write(uploadedFile);
                                //CX: write standard and preview sizes
                                ImageProcessor proc = new ImageProcessor();
                                proc.createStandardSize(uploadedFile);
                                proc.createPreviewSize(uploadedFile);
                            }
                            photos.add(new Photo(root, fileName));
                        }
                    }
                }
            }

            if (formfields != null && !StringUtils.isEmpty((String) formfields.get("s"))) {                
                if (photos != null && photos.size() > 0) {
                    for (Photo photo : photos) {
                        photoService.createBlogPhoto(blogID, photo);
                        //ServiceResponse<String> response1 = photoService.createListingPhoto(listingID, photo);                        
                    }                    
                }
            }            
        } 
        catch (Exception ex) {
            ex.printStackTrace();
        }        
        
        mav.setView(new RedirectView("blog.htm?a="+BlogAction.UPDATE_PHOTO+"&id="+blogID));
        
    }  
    
    private void updatePhoto(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {
        String id = request.getParameter("id");      
        ServiceResponse<Blog> response1 = blogService.read(id); 
        
        map.put("blog", response1.getResponse());
        mav.setViewName("blogeditphoto");
    }
    
    private void deletePhoto(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {
        String blogID = request.getParameter("blogID");
        String photoID = request.getParameter("photoID");
        ServiceResponse<Boolean> response = photoService.deleteBlogPhoto(blogID, photoID);        
        
        mav.setView(new RedirectView("blog.htm?a="+BlogAction.UPDATE_PHOTO+"&id="+blogID));
    }
    
}